﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SimpleRest.Serialization.Attributes.Annotations
{
    [AttributeUsage(AttributeTargets.Property)]
    public class LengthAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
    {
        public readonly int MinimumLength;
        public readonly int MaximumLength;

        public LengthAttribute(int minLength, int maxLength)
        {
            if (minLength < 0)
                throw new ArgumentException("The minimum length specified must be greater than or equal to 0.");
            if (maxLength < minLength)
                throw new ArgumentException("The maximum length specified must be greater than the minimum length specified.");

            this.MinimumLength = minLength;
            this.MaximumLength = maxLength;
        }

        public override bool IsValid(object value)
        {
            if (value == null)
                return false;
            if (!TypeCache.IsPrimiviteType(value.GetType()))
                throw new ArgumentException("The associated value must be a primitive type.");

            int length = value.ToString().Length;

            if (length <= MaximumLength && length >= MinimumLength)
                return true;
            return false;
        }
    }
}
